#include "ntp_time.h"
#include "global_config.h"
#include <WiFiUdp.h>
#include "WiFi.h"
#include <NTPClient.h>
#include <Arduino.h>


NtpTime ntpTime;

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
struct tm timeinfo;

void NtpTime::init() {
    Serial.print("初始化NTP时间服务器...\n");
    configTime(60*60*8, 0, "ntp3.aliyun.com");    // 用的阿里云的服务器
    Serial.println( "NTP服务器更新成功." );
}

void NtpTime::update() {
    struct tm timeinfo;
    if(!getLocalTime(&timeinfo))
    {
        Serial.println("Failed to obtain time");
        return;
    }
    Serial.println(&timeinfo, "%A, %Y-%m-%d %H:%M:%S");
}

String NtpTime::getTime() {
    struct tm timeinfo;
    if(!getLocalTime(&timeinfo))
    {
        Serial.println("Failed to obtain time");
        return "N/A";
    }
    char timeStr[20];
    sprintf(timeStr, "%04d-%02d-%02d %02d:%02d:%02d", timeinfo.tm_year+1900, timeinfo.tm_mon+1, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);
    return String(timeStr);
}